//
//  GMPlayerVoideCell.m
//  Teecloud
//
//  Created by 小熊 on 2018/11/7.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMPlayerVoideCell.h"
@interface GMPlayerVoideCell()
@property (weak, nonatomic) IBOutlet UIView *bagView;
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UIButton *redBtn;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) AVPlayer *musicPlayer;
/** 是否在播放 */
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation GMPlayerVoideCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.bagView.clipsToBounds =YES;
    self.bagView.layer.cornerRadius = 5.0;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playAudio)];
    [self.bagView addGestureRecognizer:tap];
    NSMutableArray *PicArray = [NSMutableArray new];
    for (int nums = 1; nums < 3; nums++) {//三张图片
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_voice0%d.png", nums]];
        
        [PicArray addObject:image];
    }
    _img.animationImages = PicArray;
    _img.animationDuration = 1;//一次完整动画的时长
    _img.userInteractionEnabled = YES;
}

- (AVPlayer*)musicPlayer{
    if(!_musicPlayer) {
        _musicPlayer= [AVPlayer playerWithPlayerItem:self.playerItem];
    }
    return _musicPlayer;
}
#pragma mark -懒加载，创建AVPlayerItem对象
- (AVPlayerItem*)playerItem{
    if(!_playerItem) {
        self.playerItem = [AVPlayerItem alloc];
    }
    return _playerItem;
}

-(void)setModel:(GMVoiceListModel *)model{
    _model = model;
    self.redBtn.hidden = model.IsReaded;
    CGFloat doubleTime = [self durationWithVideo:[NSURL URLWithString:model.Url]];
    self.time.text = [self getMMSSFromSS:[NSString stringWithFormat:@"%.f",doubleTime]];
    
}
-(void)playAudio{
    if (!self.model.IsReaded) {
        //如果没有读过语音，调用读语音接口
        self.readBlock();
    }
    [self.img startAnimating];
    if (!_isPlaying) {
        self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.model.Url]];
        [self.musicPlayer replaceCurrentItemWithPlayerItem:self.playerItem];
        [self.playerItem addObserver:self forKeyPath:@"status" options:0 context:NULL];
    }else{
        [self.musicPlayer pause];
        [self.img stopAnimating];
    }
    _isPlaying=!_isPlaying;
   
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSString *)totalTime{
    NSInteger seconds = [totalTime integerValue];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@′%@″",str_minute,str_second];
    return format_time;
    
}
//.实现代理方法：
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"status"]){
        switch (self.playerItem.status) {
            case AVPlayerItemStatusReadyToPlay:
            {
                [self.musicPlayer play];
                [self.img startAnimating];
                _timer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(playableCurrentTime) userInfo:nil repeats:YES];
            }
                break;
            case AVPlayerItemStatusFailed:{
                [MBProgressHUD showErrorOrSuc:@"音频加载失败" toView:self];
            }
            default:
                [MBProgressHUD showErrorOrSuc:@"未知音频格式" toView:self];
                break;
        }
        
    }
}

- (NSTimeInterval) playableCurrentTime{
    AVPlayerItem * item = self.musicPlayer.currentItem;
    if (item.status == AVPlayerItemStatusReadyToPlay) {
        NSLog(@"%f\n",CMTimeGetSeconds(self.musicPlayer.currentItem.currentTime));
        _isPlaying=NO;
        [self.playerItem removeObserver:self forKeyPath:@"status"];
        [_timer invalidate];
        [self.img stopAnimating];
        return CMTimeGetSeconds(self.musicPlayer.currentItem.currentTime);
    }else{
        return(CMTimeGetSeconds(kCMTimeInvalid));
    }
}

//获取时长
- (CGFloat)durationWithVideo:(NSURL *)videoUrl{
    AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:videoUrl options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds =CMTimeGetSeconds(audioDuration);
    return audioDurationSeconds;
}


- (void)dealloc{
    if (_isPlaying) {
        [self.playerItem removeObserver:self forKeyPath:@"status"];
    }
    [_timer invalidate];
    NSLog(@"%@释放了",self.class);
    
}
@end
